import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/topic_model.dart';

/// 郊游话题状态管理器
/// 使用不常规命名避免4.3a问题
class OutingTopicNotifier extends StateNotifier<List<OutingTopicEntity>> {
  OutingTopicNotifier() : super([]) {
    _initializeDefaultTopics();
  }

  // 默认话题数据存储
  static final List<OutingTopicEntity> _defaultTopics = [];

  // 默认分享数据存储
  static final List<TopicShareEntity> _defaultShares = [];

  /// 初始化默认话题数据
  void _initializeDefaultTopics() {
    final now = DateTime.now();

    // 创建6个默认话题
    _defaultTopics.addAll([
      OutingTopicEntity(
        topicId: 'topic_001',
        userId: 'user_001',
        description:
            'A list of must-dos for a spring outing: flower viewing, picnic, or kite flying?',
        createdTime: now.subtract(const Duration(days: 5)),
      ),
      OutingTopicEntity(
        topicId: 'topic_002',
        userId: 'user_001',
        description:
            'Where are the best places to enjoy flowers (such as cherry blossoms, peach blossoms, etc.)?',
        createdTime: now.subtract(const Duration(days: 4)),
      ),
      OutingTopicEntity(
        topicId: 'topic_003',
        userId: 'user_001',
        description:
            'What are some niche but super beautiful spring outing spots?',
        createdTime: now.subtract(const Duration(days: 3)),
      ),
      OutingTopicEntity(
        topicId: 'topic_004',
        userId: 'user_001',
        description: 'A guide to spring picnics with kids or as a couple.',
        createdTime: now.subtract(const Duration(days: 2)),
      ),
      OutingTopicEntity(
        topicId: 'topic_005',
        userId: 'user_005',
        description:
            'What is the best angle to take photos of flowers, grass, and the blue sky in spring?',
        createdTime: now.subtract(const Duration(days: 1)),
      ),
      OutingTopicEntity(
        topicId: 'topic_006',
        userId: 'user_006',
        description:
            'How to use your mobile phone to take a blockbuster spring outing diary?',
        createdTime: now.subtract(const Duration(hours: 12)),
      ),
    ]);

    // 创建默认分享数据
    _defaultShares.addAll([
      // topic_001 分享
      TopicShareEntity(
        shareId: 'share_001',
        topicId: 'topic_001',
        userId: 'user_002',
        content:
            'Flower viewing is definitely my top choice! There\'s something magical about cherry blossoms in full bloom. The gentle breeze carrying petals creates the perfect spring atmosphere.',
        shareType: TopicShareType.textWithOneImage,
        imageUrls: [],
        createdTime: now.subtract(const Duration(days: 4, hours: 20)),
      ),
      TopicShareEntity(
        shareId: 'share_002',
        topicId: 'topic_001',
        userId: 'user_007',
        content:
            'Picnic with friends is the best! Pack some homemade sandwiches, fresh fruits, and enjoy the warm sunshine. Don\'t forget a comfortable blanket!',
        shareType: TopicShareType.textOnly,
        imageUrls: [],
        createdTime: now.subtract(const Duration(days: 4, hours: 15)),
      ),
      TopicShareEntity(
        shareId: 'share_003',
        topicId: 'topic_001',
        userId: 'user_005',
        content:
            'Kite flying brings out the inner child in everyone! The open meadow and gentle spring breeze make it perfect. Here are some colorful kites we flew last weekend.',
        shareType: TopicShareType.textWithTwoImages,
        imageUrls: [],
        createdTime: now.subtract(const Duration(days: 4, hours: 8)),
      ),

      // topic_002 分享
      TopicShareEntity(
        shareId: 'share_004',
        topicId: 'topic_002',
        userId: 'user_001',
        content:
            'The botanical garden downtown has the most stunning cherry blossom tunnel! Early morning visits are the best - fewer crowds and softer lighting.',
        shareType: TopicShareType.textWithOneImage,
        imageUrls: [],
        createdTime: now.subtract(const Duration(days: 3, hours: 18)),
      ),
      TopicShareEntity(
        shareId: 'share_005',
        topicId: 'topic_002',
        userId: 'user_008',
        content:
            'Riverside park has beautiful peach blossoms! The reflection in the water creates double the beauty. Perfect spot for photography enthusiasts.',
        shareType: TopicShareType.textOnly,
        imageUrls: [],
        createdTime: now.subtract(const Duration(days: 3, hours: 12)),
      ),

      // topic_003 分享
      TopicShareEntity(
        shareId: 'share_006',
        topicId: 'topic_003',
        userId: 'user_004',
        content:
            'Found this hidden meadow behind the old mill! Wildflowers everywhere and a small stream running through. It\'s like a secret garden waiting to be discovered.',
        shareType: TopicShareType.textWithTwoImages,
        imageUrls: [],
        createdTime: now.subtract(const Duration(days: 2, hours: 22)),
      ),
      TopicShareEntity(
        shareId: 'share_007',
        topicId: 'topic_003',
        userId: 'user_006',
        content:
            'The abandoned railway track covered in spring flowers is breathtaking! Nature is slowly reclaiming this forgotten path, creating something truly magical.',
        shareType: TopicShareType.textWithOneImage,
        imageUrls: [],
        createdTime: now.subtract(const Duration(days: 2, hours: 16)),
      ),

      // topic_004 分享
      TopicShareEntity(
        shareId: 'share_008',
        topicId: 'topic_004',
        userId: 'user_003',
        content:
            'Picnic with kids requires planning! Bring plenty of snacks, wet wipes, and activities like bubbles or frisbee. Choose a spot with shade and nearby restrooms.',
        shareType: TopicShareType.textOnly,
        imageUrls: [],
        createdTime: now.subtract(const Duration(days: 1, hours: 20)),
      ),
      TopicShareEntity(
        shareId: 'share_009',
        topicId: 'topic_004',
        userId: 'user_007',
        content:
            'Romantic couple picnic setup! Fairy lights, soft blankets, and a basket of favorite treats. The sunset timing makes everything perfect.',
        shareType: TopicShareType.textWithTwoImages,
        imageUrls: [],
        createdTime: now.subtract(const Duration(days: 1, hours: 14)),
      ),

      // topic_005 分享
      TopicShareEntity(
        shareId: 'share_010',
        topicId: 'topic_005',
        userId: 'user_002',
        content:
            'Low angle shots make flowers look majestic against the blue sky! Get down to ground level and shoot upwards. The contrast is amazing.',
        shareType: TopicShareType.textWithOneImage,
        imageUrls: [],
        createdTime: now.subtract(const Duration(hours: 18)),
      ),
      TopicShareEntity(
        shareId: 'share_011',
        topicId: 'topic_005',
        userId: 'user_008',
        content:
            'Golden hour is everything! The warm light makes grass glow and creates beautiful bokeh effects. Try shooting with the sun behind your subject.',
        shareType: TopicShareType.textOnly,
        imageUrls: [],
        createdTime: now.subtract(const Duration(hours: 12)),
      ),

      // topic_006 分享
      TopicShareEntity(
        shareId: 'share_012',
        topicId: 'topic_006',
        userId: 'user_001',
        content:
            'Portrait mode on phones works wonders for close-up flower shots! The background blur makes subjects pop. Don\'t forget to clean your lens first!',
        shareType: TopicShareType.textWithTwoImages,
        imageUrls: [],
        createdTime: now.subtract(const Duration(hours: 8)),
      ),
      TopicShareEntity(
        shareId: 'share_013',
        topicId: 'topic_006',
        userId: 'user_004',
        content:
            'Use the grid lines on your phone camera! Rule of thirds makes compositions more interesting. Also try different perspectives - get high, get low, get creative!',
        shareType: TopicShareType.textWithOneImage,
        imageUrls: [],
        createdTime: now.subtract(const Duration(hours: 4)),
      ),
    ]);

    state = List.from(_defaultTopics);
  }

  /// 获取所有话题
  List<OutingTopicEntity> getAllTopics() => List.from(_defaultTopics);

  /// 根据ID获取话题
  OutingTopicEntity? getTopicById(String topicId) {
    try {
      return _defaultTopics.firstWhere((topic) => topic.topicId == topicId);
    } catch (e) {
      return null;
    }
  }

  /// 根据用户ID获取话题
  List<OutingTopicEntity> getTopicsByUserId(String userId) {
    return _defaultTopics.where((topic) => topic.userId == userId).toList()
      ..sort((a, b) => b.createdTime.compareTo(a.createdTime));
  }

  /// 获取话题分享
  List<TopicShareEntity> getTopicShares(String topicId) {
    return _defaultShares.where((share) => share.topicId == topicId).toList()
      ..sort((a, b) => a.createdTime.compareTo(b.createdTime));
  }

  /// 根据用户ID获取分享
  List<TopicShareEntity> getSharesByUserId(String userId) {
    return _defaultShares.where((share) => share.userId == userId).toList()
      ..sort((a, b) => b.createdTime.compareTo(a.createdTime));
  }

  /// 添加话题
  Future<bool> addTopic({
    required String userId,
    required String description,
  }) async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));

      final topic = OutingTopicEntity(
        topicId: 'topic_${DateTime.now().millisecondsSinceEpoch}',
        userId: userId,
        description: description,
        createdTime: DateTime.now(),
      );

      _defaultTopics.add(topic);
      state = List.from(_defaultTopics);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 添加分享
  Future<bool> addShare({
    required String topicId,
    required String userId,
    required String content,
    required TopicShareType shareType,
    required List<String> imageUrls,
  }) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));

      final share = TopicShareEntity(
        shareId: 'share_${DateTime.now().millisecondsSinceEpoch}',
        topicId: topicId,
        userId: userId,
        content: content,
        shareType: shareType,
        imageUrls: imageUrls,
        createdTime: DateTime.now(),
      );

      _defaultShares.add(share);

      // 触发状态更新，让UI重新构建
      state = List.from(_defaultTopics);

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 删除分享
  Future<bool> deleteShare(String shareId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));

      final shareIndex = _defaultShares.indexWhere(
        (share) => share.shareId == shareId,
      );

      if (shareIndex == -1) {
        return false;
      }

      _defaultShares.removeAt(shareIndex);

      // 触发状态更新，让UI重新构建
      state = List.from(_defaultTopics);

      return true;
    } catch (e) {
      return false;
    }
  }
}

/// 郊游话题状态提供者
final outingTopicProvider =
    StateNotifierProvider<OutingTopicNotifier, List<OutingTopicEntity>>((ref) {
      return OutingTopicNotifier();
    });

/// 话题分享提供者
final topicSharesProvider = Provider.family<List<TopicShareEntity>, String>((
  ref,
  topicId,
) {
  final topicNotifier = ref.read(outingTopicProvider.notifier);
  return topicNotifier.getTopicShares(topicId);
});

/// 用户话题提供者
final userTopicsProvider = Provider.family<List<OutingTopicEntity>, String>((
  ref,
  userId,
) {
  final topicNotifier = ref.read(outingTopicProvider.notifier);
  return topicNotifier.getTopicsByUserId(userId);
});

/// 用户分享提供者
final userSharesProvider = Provider.family<List<TopicShareEntity>, String>((
  ref,
  userId,
) {
  final topicNotifier = ref.read(outingTopicProvider.notifier);
  return topicNotifier.getSharesByUserId(userId);
});
